using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web;
using JoyfulHomeJourney.BackEnd.Infrastructure.Dtos.Requests;
using JoyfulHomeJourney.BackEnd.Infrastructure.Dtos.Requests.Objects;
using JoyfulHomeJourney.BackEnd.Infrastructure.Dtos.Responses;
using JoyfulHomeJourney.BackEnd.Server.Instances;
using JoyfulHomeJourney.BackEnd.Server.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using JoyfulHomeJourney.BackEnd.Infrastructure.Tools;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Security.Cryptography;
namespace JoyfulHomeJourney.BackEnd.Api.Admin.Controllers
{
	[TypeFilter(typeof(CheckLoginFilter), Arguments = new object[] { new string[] { "admin" , "employee" } })]
	public class OfflineOrdersController : BaseController
	{
		private readonly IOfflineOrdersServer _offlineOrdersServer;
		public OfflineOrdersController(IOfflineOrdersServer offlineOrdersServer)
		{
			_offlineOrdersServer = offlineOrdersServer;
		}
		
        /// <summary>
        /// 创建订单表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Addorders(RequestOfflineOrdersDto dto)    
        {
            dto.cid = _account.AId;
            return Send(await _offlineOrdersServer.AddordersAsync(dto));
        }

        /// <summary>
        /// 创建结账订单表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> add_jz_primary(add_jz_primary_DTO dto)
        {
            string uid = _account.AId;
            return Send(await _offlineOrdersServer.add_jz_primary(dto, uid));
        }

        /// <summary>
		/// 获取订单表数据
		/// </summary>
		/// <param name="page"></param>
		/// <param name="limit"></param>
		/// <returns></returns>
		[HttpGet]
        public async Task<IActionResult> Get_offline_orders(int page, int limit,string key ,string statusFilter)
        {
            string uid= _account.AId;
            return Send(await _offlineOrdersServer.Get_offline_orders(page, limit,key, statusFilter,uid));
        }
        /// <summary>
        /// 删除订单表
        /// </summary>
        /// <param id="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> dele_offline_orders(string id)
        {
            return Send(await _offlineOrdersServer.dele_offline_orders(id));
        }
        /// <summary>
		/// PC获取结账订单
		/// </summary>
		/// <returns></returns>
		[HttpGet]
        public async Task<IActionResult> Get_sys_products(string id)
        {
            string uid = _account.AId;
            return Send(await _offlineOrdersServer.Get_sys_products(id, uid));
        }
       



        /// <summary>
        /// 支付系统
        /// </summary>
        /// <returns></returns>


        /// <summary>
        /// 订单支付完成后的通知地址
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> NotifyUrl([FromForm] string trade_order_id,
            [FromForm] string total_fee,
            [FromForm] string transaction_id,
            [FromForm] string plugins,
            [FromForm] string status,
            [FromForm] string hash)
        {


            //修改成已支付
            await _offlineOrdersServer.up_offwxjz(trade_order_id, total_fee);

            return Content("success");
        }
        private long Get_Timer()
        {
            return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
        }

        private static string Sign(Dictionary<string, string> dicArray)
        {
            var prestr = new StringBuilder();
            foreach (var temp in dicArray.OrderBy(o => o.Key))
            {
                prestr.Append(temp.Key + "=" + temp.Value + "&");
            }
            var nLen = prestr.Length;
            prestr.Remove(nLen - 1, 1);
            var signValue = Md5Encoder(prestr + "4d073f520cc2e723ee13a5227bf1bd27", 32);
            return signValue;
        }
        private static string Md5Encoder(string str, int bit)
        {
            // 注册编码提供程序
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            var md5Hasher = new System.Security.Cryptography.MD5CryptoServiceProvider();
            var hashedDataBytes = md5Hasher.ComputeHash(Encoding.GetEncoding("gb2312").GetBytes(str));
            var tmp = new StringBuilder();
            foreach (var i in hashedDataBytes)
            {
                tmp.Append(i.ToString("x2"));
            }

            switch (bit)
            {
                case 16:
                    return tmp.ToString().Substring(8, 16);
                case 32:
                    return tmp.ToString();//默认情况
            }

            return string.Empty;
        }
        public class SamplesResult
        {
            public string Openid { get; set; }

            public string Url { get; set; }

            public string Errcode { get; set; }

            public string Errmsg { get; set; }

            public string Hash { get; set; }
        }
        private static string ParamData(Dictionary<string, string> dicArray)
        {
            var prestr = new StringBuilder();
            foreach (var temp in dicArray)
            {
                prestr.Append(temp.Key + "=" + temp.Value + "&");
            }

            var nLen = prestr.Length;
            prestr.Remove(nLen - 1, 1);

            return prestr.ToString();
        }
        private static string PostHttp(Dictionary<string, string> dicArray)
        {
            string result;

            try
            {
                var req = (HttpWebRequest)WebRequest.Create("https://api.xunhupay.com/payment/do.html");
                req.KeepAlive = false;
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.Accept = "application/json";

                var paramData = ParamData(dicArray);
                var data = Encoding.Default.GetBytes(paramData);

                req.ContentLength = data.Length;

                var swrite = req.GetRequestStream();
                swrite.Write(data, 0, data.Length);
                swrite.Close();

                var resp = (HttpWebResponse)req.GetResponse();
                var stream = resp.GetResponseStream();

                //获取响应内容
                var reader = new StreamReader(stream ?? throw new InvalidOperationException(), Encoding.UTF8);
                result = reader.ReadToEnd();
            }
            catch (WebException ex)
            {
                result = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 生成支付订单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Generate_Pay(Pay_Rerquest_Dto dto)
        {
            //现金支付
            if (dto.payment== "cash") {
                return Send(await _offlineOrdersServer.up_offjz(dto));
            }

            if (dto.money <= 0)
            {
                return BadRequest("参数错误");
            }
            dto.money = 0.01;

            var json = new JObject();

            //订单号
            //string pid = RandomNumber.GeneraOrderNumber3();

            try
            {
                var dic = new Dictionary<string, string>
                    {
                        {"version", "1.1"},
                        {"lang", "zh-cn"},
                        {"plugins", "test-001"},
                        {"appid", "201906136505"},//appid
	                    {"appsecret", "4d073f520cc2e723ee13a5227bf1bd27 "},//appsecret
	                    {"trade_order_id", dto.oid},//订单号
	                    {"payment", "wechat"},//支付类型
	                    {"total_fee", dto.money.ToString()},//金额
	                    {"title", "iphone"},//标题，中文需要编码“HttpUtility.UrlEncode()”
	                    {"time", Get_Timer().ToString()},//时间戳
	                    {"notify_url", "http://43.138.211.150:5851/api/OfflineOrders/NotifyUrl"},//通知链接
	                    {"return_url", "http://43.138.211.150:5851/"},//跳转链接
	                    {"nonce_str", Guid.NewGuid().ToString()},//随机字符串
	                };

                dic.Add("hash", Sign(dic));

                var sr = JsonConvert.DeserializeObject<SamplesResult>(PostHttp(dic));

                json.Add(new JProperty("openid", sr.Openid));
                json.Add(new JProperty("url", sr.Url));
                json.Add(new JProperty("errcode", sr.Errcode));
                json.Add(new JProperty("errmsg", sr.Errmsg));
                json.Add(new JProperty("hash", sr.Hash));


                return Send( ResponseApiDto.Success(
                    sr.Errmsg,
                    new  { data = sr.Url  }
                    ));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
    }
}
